<template>
  <div class="app-container">
    <div class="history">
      <el-button
        :type="params.queryType == 0 ? 'info' : 'success'"
        size="mini"
        v-waves
        @click="now"
      >消息通知</el-button>
      <el-button
        :type="params.queryType == 1 ? 'info' : 'success'"
        size="mini"
        v-waves
        @click="history"
      >历史消息通知</el-button>
    </div>
    <div class="filter-container">
      <el-button
        class="filter-item"
        v-if="~accessable.indexOf('manage:message_add')"
        type="primary"
        size="mini"
        v-waves
        icon="el-icon-plus"
        @click="handleUpdate(null)"
      >添加</el-button>

      <el-select size="mini" v-model="filters['status']" :clearable="true" placeholder="请选择状态">
        <el-option v-for="(item,index) in statusFilter" :key="index" :label="item" :value="index"></el-option>
      </el-select>

      <el-select
        size="mini"
        v-model="filters['messageType']"
        :clearable="true"
        placeholder="请选择消息类型"
      >
        <el-option v-for="(item,index) in messageType" :key="index" :label="item" :value="index"></el-option>
      </el-select>

      <el-select
        size="mini"
        v-model="filters['messageTarget']"
        :clearable="true"
        placeholder="请选择对象类型"
      >
        <el-option v-for="(item,index) in objLabel" :key="index" :label="item" :value="index"></el-option>
      </el-select>

      <el-input
        @keyup.enter.native="handleFilter"
        style="width: 200px;"
        size="mini"
        class="filter-item"
        clearable
        placeholder="消息标题"
        v-model="filters['messageTitle']"
      ></el-input>&nbsp;
      &nbsp;
      <!-- <el-checkbox v-model="filters.queryType" :true-label="1" false-label>历史记录</el-checkbox> -->

      <el-button
        class="filter-item"
        type="primary"
        v-waves
        size="mini"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="primary"
        size="mini"
        v-if="~accessable.indexOf('manage:message_export')"
        v-waves
        icon="el-icon-document"
        @click="exportExcelFile"
      >导出</el-button>
      <br />
      <br />
      <el-button
        class="filter-item"
        size="mini"
        type="primary"
        v-waves
        icon="el-icon-sort-up"
        @click="betchChangeStatus(1)"
      >批量上线</el-button>
      <el-button
        class="filter-item"
        size="mini"
        type="danger"
        v-waves
        icon="el-icon-sort-down"
        @click="betchChangeStatus(0)"
      >批量下线</el-button>
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        size="mini"
        icon="el-icon-success"
        @click="betchCheck(1)"
      >批量审核通过</el-button>
      <el-button
        class="filter-item"
        type="danger"
        size="mini"
        v-waves
        icon="el-icon-error"
        @click="betchCheck(0)"
      >批量审核拒绝</el-button>
    </div>
    <el-table
      :data="list"
      @sort-change="sortChange"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      :height="tableHeight"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column align="center" type="index" label="序号" width="80"></el-table-column>

      <el-table-column width="100" prop="messageTarget" align="center" label="对象">
        <template slot-scope="scope">{{scope.row.messageTarget | objLabelFilter }}</template>
      </el-table-column>

      <el-table-column width="100" prop="messageType" align="center" label="消息类型">
        <template slot-scope="scope">{{scope.row.messageType | usersFilter}}</template>
      </el-table-column>

      <el-table-column prop="messageTitle" align="center" label="消息标题" minWidth="120">
        <template slot-scope="scope">
          <span>{{scope.row.messageTitle}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="checkRemark" align="center" label="审核备注" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.checkRemark}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="startTime" align="center" label="开始时间" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.startTime | parseTime}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="endTime" align="center" label="失效时间" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.endTime | parseTime}}</span>
        </template>
      </el-table-column>

      <el-table-column width="100" prop="status" align="center" label="发布状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statustagFilter">{{scope.row.status|statusFilter}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column width="100" prop="checkStatus" align="center" label="审核状态">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.checkStatus | checkstatustagFilter"
          >{{scope.row.checkStatus|checkStatusFilter}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        width="280"
        class-name="small-padding"
      >
        <template slot-scope="scope">
          <div class="btns">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button
              type="primary"
              v-if="scope.row.status !==1"
              size="mini"
              @click="changeStatus(scope.row)"
            >上线</el-button>
            <el-button
              type="danger"
              v-if="scope.row.status !==0"
              size="mini"
              @click="changeStatus(scope.row)"
            >下线</el-button>
            <el-button
              type="primary"
              v-if="scope.row.checkStatus !==5"
              size="mini"
              @click="doPass(scope.row)"
            >审核通过</el-button>
            <el-button
              type="danger"
              v-if="scope.row.checkStatus !==10  && ~accessable.indexOf('message_info:check')"
              size="mini"
              @click="doReject(scope.row)"
            >审核拒绝</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.pageNo"
        :page-sizes="[10,20,30,50]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible">
      <el-form
        class="dialog-form"
        :rules="rules"
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="消息类型" prop="messageType">
          <el-select v-model="temp.messageType" placeholder="请选择">
            <el-option
              v-for="(item,index) in messageType"
              :key="index"
              :label="item"
              :value="index-0"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="temp.startTime"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                align="right"
                type="date"
                placeholder="选择生效时间"
                :picker-options="pickerOptions1"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效时间" prop="endTime">
              <el-date-picker
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                v-model="temp.endTime"
                align="right"
                type="date"
                placeholder="选择失效时间"
                :picker-options="pickerOptions1"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="发布状态" prop="status">
          <el-radio-group v-model="temp.status">
            <el-radio
              v-for="(item,value) in statusFilter"
              :key="value"
              :label="value"
              :value="value"
            >{{item}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="发布对象" prop="messageTarget">
          <el-radio-group v-model="temp.messageTarget">
            <el-radio v-for="(item,index) in objLabel" :key="index" :label="index">{{item}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="会员标签" prop="labelList" v-if="temp.messageTarget ==2">
          <el-checkbox-group v-model="temp.labelList">
            <el-checkbox v-for="item in labelListType" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="会员导入" prop="userFile" v-if="temp.messageTarget==3">
          <el-upload
            class="upload-demo"
            name="userFile"
            :action="UPLOAD_URL_FOR_USER"
            ref="upload"
            :before-upload="beforeUpload"
            :on-change="handleChangeUserFile"
            :on-success="onUploadSuccess"
            :data="postData"
            :file-list="fileList"
            :auto-upload="false"
            :show-file-list="true"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip" v-if="temp.userFile">
              <a
                :href="temp.userFile"
                target="_blank"
                style="color:blue;text-decoration:underline;"
              >已上传文件</a>
            </div>-->
          </el-upload>
        </el-form-item>

        <el-row :gutter="20" v-if="temp.messageType == 1">
          <el-col :span="12">
            <el-form-item label="封面(345*108)" prop="coverImg">
              <el-upload
                class="avatar-uploader"
                :action="UPLOAD_URL"
                :show-file-list="false"
                :on-success="handleAvatarSuccess('coverImg')"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="temp.coverImg" :src="temp.coverImg|absUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模板类型" prop="templateId" v-if="temp.messageType == 2">
          <el-radio-group v-model="temp.templateId">
            <el-radio
              v-for="(item,value) in templateType"
              :key="value"
              :label="value"
              :value="value.id"
            >{{item.templateTitle}}</el-radio>
          </el-radio-group>
          <el-button size="small" type="primary" @click="resetForm">重置</el-button>
        </el-form-item>
        <el-form-item label="消息标题" prop="messageTitle">
          <el-input v-model="temp.messageTitle"  placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="消息内容" prop="messageContent ">
          <div class="quill-wrap" style="height:350px;">
            <quill-editor
              style="height:300px;"
              v-model="temp.messageContent "
              ref="myQuillEditor"
              :options="editorOption"
            ></quill-editor>
          </div>
        </el-form-item>
        <el-form-item label="消息链接" prop="messageLinkUrl" v-if="temp.messageType === 1">
          <el-input v-model="temp.messageLinkUrl"  placeholder="请输入消息跳转链接"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitFormAction">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
.avatar-uploader {
  width: 375px;
  height: 155px;
}

.avatar-uploader >>> .avatar {
  width: 375px;
  height: 155px;
}

.avatar-uploader >>> .avatar-uploader-icon {
  width: 375px;
  height: 155px;
}
.img-src {
  width: 100px;
}
.btns /deep/ button {
  margin-top: 10px;
  margin-bottom: 10px;
}
.history {
  margin-bottom: 10px;
}
</style>

<script>
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
// import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
import {
  paymentTypes,
  auditStatus,
  choiceType,
  labeledGoods
} from '../../config/constants';

import { quillEditor, Quill } from 'vue-quill-editor';
import { parseTime } from '../../filters';
let statusFilter = ['下线', '上线']

let objLabel = { '1': '全部会员', '2': '会员标签', '3': '指定编号会员' }
let templateType = [
  '积分变动通知',
  '积分到期提醒',
  '积分兑换通知',
  '产品变动通知'
]
let checkStatusType = ['待审核', '审核通过', '审核拒绝']

const cityOptions = ['上海', '北京', '广州', '深圳']
let statustagFilter = ['danger', 'success', 'info', 'warning']

let messageType = { '1': '优惠活动', '2': '个人消息', '3': '通知公告' }

let userstagFilter = ['success']
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      tableHeight: 700,
      headers: 'Content-Type: multipart/form-data',
      postData: {},
      multipleSelection: [],
      labelList: [],
      checkAll: false,
      checkedCities: ['上海', '北京'],
      labelListType: [],
      total: 0,
      UPLOAD_URL_FOR_USER: '',
      choiceType,
      fileList: [],
      formData: '',
      fomrList: [],
      dialogFormVisibleDetail: false,
      form: {},
      temp: {
        labelListType: [],
        id: '',
        labelList: [],
        // users: "",
        title: '',
        endTime: '',
        startTime: '',
        messageType: '',
        messageName: '',
        messageTarget: '',
        queryType: '',
        status: '',
        templateId: '',
        coverImg: '',
        messageTitle: '',
        messageContent: '',
        messageLinkUrl: '',
        userFile: ''
      },
      editorOption: {
        placeholder: '在这里输入内容',
        modules: {
          // ImageExtend: {
          //   loading: true,
          //   name: "file",
          //   action: this.UPLOAD_URL,
          //   response: res => {
          //     return res.info;
          //   }
          // }
          // ,
          // toolbar: {
          //   container: container,
          //   handlers: {
          //     image: function() {
          //       QuillWatch.emit(this.quill.id);
          //     }
          //   }
          // }
        }
      },
      pickerOptions1: {
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      marketingType: '',
      params: { marketingType: this.marketingType, pageNo: 1, pageSize: 10 },
      statusFilter: statusFilter,
      templateType: templateType,
      cityIdOptions: [],
      objLabel: objLabel,
      messageType: messageType,

      rules: {
        messageType: [
          {
            required: true,
            message: '消息类型不能为空',
            trigger: 'change'
          }
        ],
        messageTitle: [
          {
            required: true,
            message: '消息标题不能为空',
            trigger: 'change'
          }
        ],
        startTime: [
          {
            required: true,
            message: '开始时间不能为空',
            trigger: 'change'
          }
        ],
        endTime: [
          {
            required: true,
            message: '截止时间不能为空',
            trigger: 'change'
          }
        ],
        messageTarget: [
          {
            required: true,
            message: '发布对象不能为空',
            trigger: 'change'
          }
        ],
        // userFile: [
        //   {
        //     required: true,
        //     message: '导入会员不能为空',
        //     trigger: 'change'
        //   }
        // ],
        messageContent: [
          {
            required: true,
            message: '消息内容不能为空',
            trigger: 'change'
          }
        ],
        // messageLinkUrl: [
        //   {
        //     required: true,
        //     message: '消息链接不能为空',
        //     trigger: 'change'
        //   }
        // ],
        coverImg: [
          {
            required: true,
            message: '封面不能为空',
            trigger: 'change'
          }
        ],
        status: [
          {
            required: true,
            message: '请选中发布状态',
            trigger: 'change'
          }
        ]
      }
    }
  },
  created () {
    this.params.queryType = 1

    this.init('message_info', 1).loadData()

    this.setFilterAsPostParam()
    this.$get('/admin/goods_theme/label_list').then(data => {
      this.labelListType = data
    })

    this.$post('/admin/message_info/template/list', this.params).then(data => {
      this.templateType = data.rows
    })
    this.tableHeight = window.innerHeight - 340
  },
  filters: {
    statusFilter (status) {
      return statusFilter[parseInt(status)]
    },
    templateType (status) {
      return templateType[parseInt(status)]
    },

    statustagFilter (status) {
      return statustagFilter[parseInt(status)]
    },
    usersFilter (status) {
      return messageType[parseInt(status)]
    },
    objLabelFilter (status) {
      return objLabel[parseInt(status)]
    },

    adPositiontagFilter (status) {
      return adPositiontagFilter[parseInt(status)]
    },
    checkStatusFilter (status) {
      return { 0: '待审核', 5: '审核通过', 10: '审核拒绝' }[status]
    },
    checkstatustagFilter (status) {
      return { 0: 'default', 5: 'success', 10: 'danger' }[status]
    }
  },
  methods: {
    beforeUpload (file) {
      // this.fileList.length = 0
    },
    handleChangeUserFile (file, fileList) {
      this.temp.userFile = file.raw
      this.fileList = fileList.slice(-1)
      console.log(this.fileList)
    },
    resetForm () {
      this.temp.templateId = '';
    },
    now () {
      this.params.queryType = 1
      this.handleFilter()
    },
    history () {
      this.params.queryType = 0
      this.handleFilter()
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    betchCheck (checkResult) {
      var ids = []
      this.multipleSelection.forEach(el => {
        ids.push(el.id)
      })
      var id = ids.join(',')
      this.$post('/admin/message_info/batch_check', {
        id: id,
        checkResult: checkResult
      }).then(data => {
        this.isEditing = false
        this.loadData()
      })
    },
    betchChangeStatus (status) {
      var ids = []
      this.multipleSelection.forEach(el => {
        ids.push(el.id)
      })
      var id = ids.join(',')
      this.$post('/admin/message_info/batch_modify_status', {
        id: id,
        status: status
      }).then(data => {
        this.loadData()
      })
    },
    changeStatus (row) {
      var status = row.status
      if (status == 0) {
        status = 1
      } else {
        status = 0
      }
      this.$post('/admin/message_info/modify_status', {
        id: row.id,
        status: status
      }).then(data => {
        this.loadData()
      })
    },
    queryDetail (datail, callback) {
      this.dialogFormVisibleDetail = true
      var id = datail.id
      this.$post('/admin/message_info/detail', { id }).then(data => {
        this.fomrList = data.row || data
        callback && callback(data)
      })
    },
    handleUpdate (el) {
      if (el) {
        el.messageName = messageType[el.messageType]
        el.messageTarget = el.messageTarget.toString()
        this.isEditing = true
        el.startTime && (el.startTime = parseTime(el.startTime))
        el.endTime && (el.endTime = parseTime(el.endTime))
        this.$post('/admin/message_info/detail', { id: el.id }).then(data => {
          el.labelList = data.labelList || []
          el.labelList &&
            (el.labelList = el.labelList.map(i => {
              return i.labelId
            }))
          Object.assign(this.temp, el)
          this.temp.labelList = el.labelList
        })
      } else {
        this.isEditing = false
        Object.keys(this.temp).forEach(key => {
          if (key === 'labelList') {
            this.temp[key] = []
          } else {
            this.temp[key] = '';
          }
        })
      }
      this.dialogFormVisible = true
    },

    onUploadSuccess (res, file, list) {
      this.submiting = false
      if (res.errcode === 1) {
        this.$message.error(res.msg)
        return;
      }
      list.length = 0
      this.loadData()
      this.$$notify('操作成功')
      this.dialogFormVisible = false
    },
    requestFile (file) {
      console.log(file)
    },

    findNameByLabelId (id) {
      let rt = '';
      this.labelList.every(el => {
        if (el.id == id) {
          rt = el.name
          return false
        }
        return true
      })
      return rt
    },
    submitFormAction () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          // console.log(valid)
          // console.log(this.temp)
          // this.temp.forEach(el =>{
          //   console.log(el)
          //   this.formData=el
          // })
          let postData = Object.assign({}, this.temp)
          if(this.labelListType !== null){
            this.labelListType
            .filter(el => postData.labelList.indexOf(el.id) !== -1)
            .forEach((el, idx) => {
              postData['labelList[' + idx + '].labelId'] = el.id
              postData['labelList[' + idx + '].labelName'] = el.name
            })
          }
          // this.labelListType
          //   .filter(el => postData.labelList.indexOf(el.id) !== -1)
          //   .forEach((el, idx) => {
          //     postData['labelList[' + idx + '].labelId'] = el.id
          //     postData['labelList[' + idx + '].labelName'] = el.name
          //   })
          // postData.append("id",el.id)
          postData.marketingType = this.marketingType
          let url = '/admin/message_info/add';
          if (this.isEditing) {
            url = '/admin/message_info/modify';
            postData.templateId = '';
          }
          // postData.append("userfile",this.temp.userFile)
          if (postData.messageType != 2) {
            delete postData.templateId
          }

          delete postData.labelList
          if (this.temp.messageTarget == 3) {
            // let formData = new FormData()
            // Object.keys(postData).forEach(key => {
            //   formData.append(key, postData[key])
            // })
            // // this.$post(url,formData)
            // postData = formData
            postData = Object.keys(postData).reduce(
              (a, b) => (a.append(b, postData[b]), a),
              new FormData()
            )
            // return;
          } else {
            delete postData.userFile
          }
          this.$post(url, postData)
            .then(data => {
              this.loadData()
              this.$$notify('操作成功')
              this.dialogFormVisible = false
            })
            .finally(_ => {
              this.submiting = false
            })
        }
      })
    },
    doPass (row) {
      this.$prompt('审核备注', '确认审核通过吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.$post('/admin/message_info/check', {
            id: row.id,
            checkResult: 1,
            remark: value
          }).then(data => {
            this.$$notify('审核通过成功')
            this.loadData()
          })
        })
        .catch(() => {})
    },
    doReject (row) {
      this.$prompt('审核备注', '确认审核拒绝吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.$post('/admin/message_info/check', {
            id: row.id,
            checkResult: 0,
            remark: value
          }).then(data => {
            this.$$notify('审核拒绝成功')
            this.loadData()
          })
        })
        .catch(() => {})
    },
    handleCurrentChange () {
      this.loadData()
    },
    exportExcelFile () {
      this.exportExcel1({
        title: '消息管理',
        fields: [
          {
            field: 'title',
            title: '消息标题'
          },
          {
            field: 'createStartTime',
            title: '开始时间'
          },
          {
            field: 'createEndTime',
            title: '截止时间'
          },
          {
            field: 'status',
            title: '发布状态',
            valueMap: ['上线', '下线']
          },
          {
            field: 'messageTarget',
            title: '消息目标类型'
          },
          {
            field: 'queryType',
            title: '查询消息类型'
          },
          {
            field: 'messageType',
            title: '消息类型'
          }
        ]
      }).then(info => {
        this.openWin(info)
      })
    }
  }
}
</script>
